package knapsackga;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class Knapsack
{
    private int _num_objects = 0;

    private int _max_weight = 0;

    private List<KnapsackObject> _objects = null;

    public Knapsack( String definition_file )
    {
        String line = null;
        try
        {
            BufferedReader file = new BufferedReader( new FileReader(
                    definition_file ) );

            /* Grab the maximum weight the knapsack can hold */
            line = file.readLine();
            _max_weight = Integer.parseInt( line );

            /* Load in all the objects defined in the file */
            _objects = new ArrayList<KnapsackObject>( 50 );
            while( ( line = file.readLine() ) != null )
            {
                String[] weight_value = line.split( " " );
                int weight = Integer.parseInt( weight_value[0] );
                int value = Integer.parseInt( weight_value[1] );

                _objects.add( new KnapsackObject( weight, value ) );
            }

            _num_objects = _objects.size();

        }
        catch( FileNotFoundException e )
        {
            System.out.println( "Failed to find Knapsack definition file ["
                    + definition_file + "]" );
            throw new RuntimeException( e );
        }
        catch( NumberFormatException e )
        {
            System.out.println( "Parse error reading Knapsack definition file ["
                    + definition_file
                    + "] Failed to parse ["
                    + line
                    + "] wrong number format." );
            throw new RuntimeException( e );
        }
        catch( IOException e )
        {
            System.out.println( "Error reading Knapsack definition file ["
                    + definition_file + "]" );
            throw new RuntimeException( e );
        }

    }

    /**
     * Returns an object out of all possible objects to be placed in the
     * knapsack.
     * 
     * @param index
     * @return
     */
    public KnapsackObject getObject( int index )
    {
        return _objects.get( index );
    }

    /**
     * Return the total number of objects that must be selected from.
     * 
     * @return
     */
    public int getNumberOfObjects()
    {
        return _num_objects;
    }

    /**
     * Returns the maximum weight that can be placed in the knapsack.
     * 
     * @return
     */
    public int getMaxWeight()
    {
        return _max_weight;
    }
}
